#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time   : 2021/7/24 16:20
# @Author : cjw
"""
使用ORM操作MySQL数据库，实现自定义的分页器
"""
import math

from sqlalchemy import func, select
from sqlalchemy.orm import Session
from loguru import logger


class Paginator:

    def __init__(self, stmt, session: Session, page_size: int = 10):
        """
        :param stmt: 构造的查询对象
        :param session: 使用session来操作数据库
        :param page_size: 每一页数据量的大小，默认为10
        """
        self.stmt = stmt
        self.session = session
        self.page_size = page_size

    @property
    def data_count(self):
        """ 总记录数 """
        stmt = select(func.count().label('data_count')).select_from(self.stmt)
        rs = self.session.execute(stmt).mappings().one()
        return rs.get('data_count')

    @property
    def page_count(self):
        """ 总页数 """
        return math.ceil(self.data_count / self.page_size)

    def page(self, page: int = 1):
        """
        查询当前页的数据
        :param page: 当前页码
        :return: list[dict])
        """
        if page < 1:
            logger.error(msg := f'当前页码不正确：{page}，小于1')
            raise ValueError(msg)
        if page > (page_count := self.page_count):
            logger.error(msg := f'当前页码不正确：{page}，大于总页数：{page_count}')
            raise ValueError(msg)
        offset = (page - 1) * self.page_size
        stmt = self.stmt.offset(offset).limit(self.page_size)
        return self.session.execute(stmt).scalars()
